package com.daisuxia.task;

import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.JSON;
import com.daisuxia.back.utils.SysCacheUtils;
import com.daisuxia.back.utils.WebClient;
import com.daisuxia.web.pojo.BackConfigParams;
import com.daisuxia.web.pojo.BorrowOrder;
import com.daisuxia.web.pojo.OutOrders;
import com.daisuxia.web.pojo.Repayment;
import com.daisuxia.web.pojo.User;
import com.daisuxia.web.pojo.p2p.LoanPackageStatusRequest;
import com.daisuxia.web.pojo.p2p.LoanPackageStatusResponse;
import com.daisuxia.web.service.IBorrowOrderService;
import com.daisuxia.web.service.IRepaymentService;
import com.daisuxia.web.service.IUserService;
import com.daisuxia.web.util.DateUtil;
import com.daisuxia.web.util.MapConvertCoreUtils;
import com.daisuxia.web.util.PMD5Utils;
import com.daisuxia.web.util.SendSmsUtil;

import redis.clients.jedis.JedisCluster;

/** 
 * P2P
 * @author hj 
 */
public class P2PApiTaskService {
	private static Logger logger = LoggerFactory.getLogger(P2PApiTaskService.class);
	@Autowired
	private IBorrowOrderService borrowOrderService;
	@Autowired
	private IRepaymentService repaymentService;
	@Autowired
	public IUserService userService;
	@Autowired
	JedisCluster jedisCluster;

	int day = 2 * 60 * 24;

	/**
	 * p2p回调，轮询
	 * @author zhangsh Tel:13817876783
	 * @date 2017年9月14日 上午9:25:16
	 * @Title updateLoanTermCallBack
	 * @Description  void 
	 * @throws
	 */
	public void updateLoanTermCallBack() {
		
	
		String  updateLoanTermKey="updateLoanTermCallBack" ;
		if(jedisCluster.get(updateLoanTermKey)!=null){
			logger.info("------ last  updateLoanTermCallBack is running");
			return;
		}
		
		
		logger.info("------ updateLoanTermCallBack start running");
		HashMap<String, Object> paramsM = new HashMap<String, Object>();
		paramsM.put("borrowStatus", BorrowOrder.STATUS_FKZ);
		paramsM.put("payStatus", BorrowOrder.SUB_PAY_DDJG);
		paramsM.put("queryType", "subPay");
		// paramsM.put("bankIscmb", 2);
		paramsM.put("querylimit", 5);
		
		List<BorrowOrder> bos = borrowOrderService.findAll(paramsM);
		
		for (BorrowOrder borrowOrder : bos) {
			if(jedisCluster.get(borrowOrder.getOutTradeNo())!=null){
				logger.info("------ last  updateLoanTermCallBack is running,outNumber :" +borrowOrder.getOutTradeNo());
				continue;
			}
			
			try {

				LoanPackageStatusRequest loanPackageStatusRequest = new LoanPackageStatusRequest();
				// loanPackageStatusRequest.setPack_no("6203589521117711771");
				loanPackageStatusRequest.setType("item");
				loanPackageStatusRequest.setUser_apply_no(borrowOrder.getOutTradeNo());

				String pxh = MapConvertCoreUtils.createLinkString(
						MapConvertCoreUtils.paraFilter(MapConvertCoreUtils.object2Map(loanPackageStatusRequest)));

				LinkedHashMap<String, String> mapApi = SysCacheUtils.getConfigParams(BackConfigParams.YANGYUE_MDL_API);
				String url = mapApi.get(BackConfigParams.MDL_POST_URL);
				String _client_ = mapApi.get(BackConfigParams.MDL_SYS_CLIENT);
				String key = mapApi.get(BackConfigParams.MDL_SYS_KEY);
				String _cmd_ = mapApi.get(BackConfigParams.MDL_LOAN_PACKAGE_STATUS);
				String _deviceid_ = mapApi.get(BackConfigParams.MDL_SYS_DEVICEID);
				String sign = PMD5Utils.encodeByMD5(_client_ + "|" + key + "|" + _cmd_ + "|" + pxh);
				Map<String, Object> mm = new HashMap<String, Object>();

				mm = MapConvertCoreUtils.object2Map(loanPackageStatusRequest);
				mm.put("_client_", _client_);
				mm.put("_cmd_", _cmd_);
				mm.put("_deviceid_", _deviceid_);
				mm.put("_sign_", sign);
				Map<String, String> w = MapConvertCoreUtils.object2MapString(mm);
				logger.info("p2p request parameter : " + w+", url = "+url);
				String rt = WebClient.getInstance().doPost(url, w);
                //p2p接口偶尔会出现返回null
				if(rt!=null){
					jedisCluster.setex(borrowOrder.getOutTradeNo(),30, borrowOrder.getOutTradeNo());
					LoanPackageStatusResponse loanNotifyResponse = JSON.parseObject(rt, LoanPackageStatusResponse.class);
					logger.info("p2p callback result : " + loanNotifyResponse.toString());
					String orderNumber = loanNotifyResponse.getDataresult().getUser_apply_no();
					if ("0".equals(String.valueOf(loanNotifyResponse.getErrorcode()))) {
						Date fkDate = new Date();

						String code = loanNotifyResponse.getDataresult().getStatus();
						if ("2".equals(code)) {

							// BorrowOrder borrowOrderR =
							// borrowOrderService.findOneBorrow(Integer.parseInt(borrowId));
							BorrowOrder borrowOrderR = borrowOrderService.selectByOutOrderNumber(orderNumber);
							// // 更新或者添加操作
							if (borrowOrderR != null) {
								if (borrowOrderR.getStatus().intValue() != BorrowOrder.STATUS_HKZ.intValue()) {// 放款成功

									borrowOrderR.setLoanTime(fkDate);
									borrowOrderR.setStatus(BorrowOrder.STATUS_HKZ);
									borrowOrderR.setPaystatus(BorrowOrder.SUB_PAY_FKCG);
									borrowOrderR.setLoanEndTime(DateUtil.addDay(fkDate, borrowOrderR.getLoanTerm()));// 放款时间加上借款期限
									String invest_name = null == loanNotifyResponse.getDataresult().getInvest_name() ? "" : loanNotifyResponse.getDataresult().getInvest_name();
									borrowOrderR.setPayRemark("invest_name:"+invest_name);
									
									Repayment repayment = new Repayment();
									repayment.setUserId(borrowOrderR.getUserId());
									repayment.setAssetOrderId(borrowOrderR.getId());
									repayment.setRepaymentAmount(Long.valueOf(borrowOrderR.getMoneyAmount()));
									repayment.setRepaymentedAmount(0L);
									repayment.setRepaymentPrincipal(Long.valueOf(borrowOrderR.getIntoMoney()));
									repayment.setRepaymentInterest(Long.valueOf(borrowOrderR.getLoanInterests()));
									repayment.setLateFeeApr(borrowOrderR.getLateFeeApr());
									repayment.setRepaymentTime(DateUtil.addDay(fkDate, borrowOrderR.getLoanTerm()));// 放款时间加上借款期限
									repayment.setCreatedAt(fkDate);
									repayment.setUpdatedAt(fkDate);
									repayment.setPeriod(borrowOrderR.getLoanTerm());
									repayment.setStatus(borrowOrderR.getStatus());
									// 预防有重复的还款订单产生
									Repayment repaymen = repaymentService.selectByAssetOrderId(borrowOrderR.getId());
									if (null == repaymen) {
										repaymentService.insertSelective(repayment);
										User user = userService.searchByUserid(borrowOrderR.getUserId());
										SendSmsUtil.sendSmsDiyCL(user.getUserPhone(),
												"你收到贷速侠打款" + borrowOrderR.getIntoMoney() / 100.00 + "元,预计很快到账，请注意查收！");

									} 
								}
								borrowOrderService.updateById(borrowOrderR);

							} else {

								logger.info("放款回调，没有找到对应的借款信息：");
							}

						} /*
							 * else if ("0".equals(code) || "1".equals(code)) {
							 * borrowOrder.setId(borrowOrder.getId());
							 * borrowOrder.setUpdatedAt(new Date());
							 * borrowOrder.setStatus(BorrowOrder.STATUS_FKZ);
							 * borrowOrder.setPaystatus(BorrowOrder.SUB_PAY_DDJG);
							 * borrowOrderService.updateById(borrowOrder);
							 * 
							 * }
							 */
					} /*else {
						borrowOrder.setId(borrowOrder.getId());
						borrowOrder.setUpdatedAt(new Date());
						borrowOrder.setStatus(BorrowOrder.STATUS_FKSB);
						borrowOrder.setPaystatus(BorrowOrder.SUB_PAY_QQSB);
						borrowOrderService.updateById(borrowOrder);

					}*/
					jedisCluster.del(borrowOrder.getOutTradeNo());
				}
			} catch (Exception e) {
				jedisCluster.del(borrowOrder.getOutTradeNo());
				logger.info("borrow Id EXCEPTION = " + borrowOrder.getOutTradeNo(), e);
				/*borrowOrder.setUpdatedAt(new Date());
				borrowOrder.setStatus(BorrowOrder.STATUS_FKSB);
				borrowOrder.setPaystatus(BorrowOrder.SUB_PAY_QQSB);
				borrowOrderService.updateById(borrowOrder);*/
			}
		}
		
		jedisCluster.del(updateLoanTermKey);

	}

	/**
	 * 打包放款
	 * @author zhangsh Tel:13817876783
	 * @date 2017年9月14日 下午4:15:00
	 * @Title updateLoanTerm
	 * @Description  void 
	 * @throws
	 */
	public void updateLoanTerm() {
		Date nowDate = new Date();
		int nowHour = nowDate.getHours();
		int monutes = nowDate.getMinutes();
		// 避免交替日打款错误，23点55到第二天0点05分期间，不打款
		if (nowHour == 23) {
			if (monutes > 55) {
				return;
			}

		}

		if (nowHour == 0) {
			if (monutes < 5) {
				return;
			}

		}

		String packageNoKey = "package_no_key_dbfk";
		logger.info("updateAnalysis is running");

		if (jedisCluster.get(packageNoKey) != null) {
			logger.info("last updateLoanTerm is running");
		} else {

			LinkedHashMap<String, String> mapApi = SysCacheUtils.getConfigParams(BackConfigParams.YANGYUE_MDL_API);
			String userFeeIsopen = mapApi.get(BackConfigParams.MDL_API_ISOPEN);
			String assetSize = mapApi.get(BackConfigParams.MDL_ASSET_SIZE);

			if (!userFeeIsopen.equals("1")) {
				logger.info("CMB  loan_user is  close P2P打款已关闭！");
				return;
			}
			logger.info("begin   updateLoanTerm  ======");
			// 非招行打款
			HashMap<String, Object> paramsM = new HashMap<String, Object>();
			paramsM.put("borrowStatus", BorrowOrder.STATUS_FKZ);
			paramsM.put("payStatus", BorrowOrder.SUB_PAY_CSZT);
			paramsM.put("queryType", "subPay");
			try {
				int loanTerms[] = BorrowOrder.LOAN_TREMS;

				try {

					for (int loanTerm : loanTerms) {
						// paramsM.put("bankIscmb", 2);
						paramsM.put("loanTerm", loanTerm);
						paramsM.put("querylimit", Integer.valueOf(assetSize));
						List<BorrowOrder> bos = borrowOrderService.findAll(paramsM);
						if (bos != null && bos.size() > 0) {

							logger.info("begin   Loan  ======" + OutOrders.act_NTQRYEBP_A);

							borrowOrderService.requestPaysNotCmbUser(bos, loanTerm);
							// 删除此批次包
							jedisCluster.del(packageNoKey);

							logger.info("end   Loan  ======" + OutOrders.act_NTQRYEBP_A);
						}
						// Thread.sleep(1000);
						// 查询非招行状态

					}
					// queryPaysStateNotCmb();
				} catch (Exception e) {
					jedisCluster.del(packageNoKey);
					logger.error("error   Loan  ======" + OutOrders.act_NTQRYEBP_A + e.getMessage());
				}

			} catch (Exception e) {
				jedisCluster.del(packageNoKey);
				logger.error("updateLoanTerm error", e);
			} finally {
				jedisCluster.del(packageNoKey);
			}
			logger.info("end   updateLoanTerm  ======");
		}

	}

}